import useStatAnswerData from '@/store/stat-answer-data'
import { QUESTION_TYPE_MATRIX_RADIO } from '@/constants/default'
import { formatTime, serialLetter } from '@/utils/utils'

/*
获取问卷, 核心内容如下:
  {
    title
    questions: [ 这里包括了 "description" 类型的问题
      {
        type
        title
        options:[ {id, text} ]
        subTitles: [ {id, text} ]
      }
    ]
  }
将上面内容格式化成这种形式:
  ['填写时间', '问题1', '问题2', '问题3']
  增加一个 '填写时间'
  其中的多选题拆分出来, 有几个选项就有几个问题, 将问题标题和答案拼接起来
  矩阵单选也是一样, 将主标题和子标题拼接起来
*/
function getQuestionList(survey) {
  const surveyTitle = survey.title
  const questionList = ['填写时间']

  survey.questions.forEach(q => {
    if (
      q.type === QUESTION_TYPE_SINGLE ||
      q.type === QUESTION_TYPE_SELECT ||
      q.type === QUESTION_TYPE_TEXT ||
      q.type === QUESTION_TYPE_TEXTAREA
    ) {
      questionList.push(q.title)
    } else if (q.type === QUESTION_TYPE_MULTI) {
      q.options.forEach(o => {
        questionList.push(q.title + ': ' + o.text)
      })
    } else if (q.type === QUESTION_TYPE_MATRIX_RADIO) {
      q.subTitles.forEach(s => {
        questionList.push(q.title + ': ' + s.text)
      })
    }
  })

  return {
    questionList,
    surveyTitle,
  }
}

/*
原本的数据格式:
answers 结构如下:
  [
    { answers: [ {
      type,
      text,
      options: [{id, text}],
      groups: [{options: [{id, text}]}],
    }]}
  ]

要格式化成以下格式:
[
  ['填写时间', '答案1', '答案2']
  其中多选题有多少项就输出多少项答案, 如果该答案没选, 则为空字符串
  矩阵单选每个子问题的答案都拆分出来.
]
*/
function getAnswerList(answers, survey) {
  const answerList = []
  answers.forEach(oneAnswer => {
    const answerLi = [formatTime(oneAnswer.collect_time)]
    oneAnswer.answer.forEach(a => {
      if (a.type === QUESTION_TYPE_TEXT || a.type === QUESTION_TYPE_TEXTAREA) {
        answerLi.push(a.text)
      } else if (
        a.type === QUESTION_TYPE_SINGLE ||
        a.type === QUESTION_TYPE_SELECT
      ) {
        answerLi.push(a.options[0].text)
      } else if (a.type === QUESTION_TYPE_MATRIX_RADIO) {
        a.groups.forEach(g => {
          answerLi.push(g.options[0].text)
        })
      } else if (a.type === QUESTION_TYPE_MULTI) {
        survey.questions.some(q => {
          if (q.id == a.id) {
            q.options.forEach(o => {
              if (a.options.some(({ id }) => id == o.id)) {
                answerLi.push(o.text)
              } else {
                answerLi.push('')
              }
            })
            return true
          }
        })
      }
    })
    answerList.push(answerLi)
  })
  return answerList
}

/*

statOptionsNum 结构如下:
{
  主问题id: {
    子问题id: {
      选项id: 0 统计选项数量
    }
  }
}
而下面三项, 用于保存 id 对应的标题/选项值
statTitles 问题标题
statSubTitles 问题子标题
statOptionName 问题选项

*/
function formatSummary(survey, answers) {
  const statOptionsNum = {}
  const statTitles = {}
  const statSubTitles = {}
  const statOptionName = {}
  const titlesId = []
  const subTitlesId = {}
  const optionsId = {}
  let maxOptionNum = 0 // TODO: 还未处理选项数不一致的情况
  survey.questions.forEach(q => {
    // q.id 是主问题id
    if (q.type === QUESTION_TYPE_MATRIX_RADIO) {
      if (maxOptionNum < q.options.length) maxOptionNum = q.options.length
      titlesId.push(q.id)

      const countOptions = {}
      statTitles[q.id] = q.title
      statOptionsNum[q.id] = {}
      subTitlesId[q.id] = []
      optionsId[q.id] = []

      q.options.forEach(o => {
        // o.id 是选项id
        statOptionName[o.id] = o.text
        countOptions[o.id] = 0
        optionsId[q.id].push(o.id)
      })
      q.subTitles.forEach(s => {
        // s.id 是子问题id
        subTitlesId[q.id].push(s.id)
        statSubTitles[s.id] = s.text
        // NOTE: 在将一个对象作为初始化赋值时, 一定要注意深度克隆
        statOptionsNum[q.id][s.id] = JSON.parse(JSON.stringify(countOptions))
      })
    }
  })
  answers.forEach(oneAnswer => {
    oneAnswer.answer.forEach(a => {
      // a.id 是是主问题id
      if (a.type === QUESTION_TYPE_MATRIX_RADIO) {
        a.groups.forEach(g => {
          // g.id 是子问题id
          // g.options[0].id 是 选项id
          // 当矩阵单选题是 "选填" 时, g.options 可能是空数组
          const i = g.options[0]?.id
          if (i === undefined) return
          console.log('debugger: ', g.id)
          statOptionsNum[a.id][g.id][i]++
        })
      }
    })
  })

  const result = []

  titlesId.forEach(ti => {
    const t = []
    optionsId[ti].forEach((oi, i) => {
      t.push(serialLetter(i) + '. ' + statOptionName[oi])
    })
    result.push([statTitles[ti], ...t])

    subTitlesId[ti].forEach(si => {
      const oNum = []
      optionsId[ti].forEach((oi, i) => {
        oNum.push('' + statOptionsNum[ti][si][oi])
      })
      result.push([statSubTitles[si], ...oNum])
    })
  })

  console.log('debugger: ', result)
  return result
}

export default async function () {
  const statAnswerData = useStatAnswerData()
  const survey = JSON.parse(JSON.stringify(statAnswerData.survey))
  const answers = JSON.parse(JSON.stringify(statAnswerData.answers))

  const matrix = formatSummary(survey, answers)
  let csv = ''
  matrix.forEach(row => {
    row.forEach(item => {
      let text = ''
      for (const ch of item) {
        if (ch === ',') text += '，'
        else if (ch === '\n') text += ' '
        else text += ch
      }
      csv += text + ','
    })
    csv += '\n'
  })

  const a = document.createElement('a')
  const blob = new Blob(['\uFEFF', csv], { type: 'text/csv' })

  a.download = `${survey.title}-汇总表格.csv`
  a.href = URL.createObjectURL(blob)
  a.click()
  URL.revokeObjectURL(a.href)

  return
}
